﻿package com.aigeth;

import cn.hutool.http.HttpUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsResponse.Record;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import java.io.*;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

public class UpdateDoaminIpStarted {
    static String ACCESS_KEY_ID = "";//需要去阿里控制台 》 AccessKey管理 获取
    static String ACCESS_KEY_SECRET = "";//需要去阿里控制台 》 AccessKey管理 获取
    static String REGION_ID = "cn-zhengzhou";
    static String DOMIAN = "ai.com";//域名  改成你的域名
    static final Map<String, String> UPDATE_DOMIANS = new HashMap<>();

    private static IAcsClient client = null;

    private static String jarPath = "";

    static {
        try {
            jarPath = UpdateDoaminIpStarted.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
            Integer len = jarPath.lastIndexOf("/");
            if (len < 0) {
                len = jarPath.lastIndexOf("\\");
            }
            jarPath = jarPath.substring(0, len) + "/";

            Map<String, Object> ymlData = new HashMap<>();

            File file = new File(jarPath + "application.yml");
            if (file.exists()) {
                try (InputStream content = new FileInputStream(file)) {
                    Yaml yaml = new Yaml(new Constructor(Map.class));
                    Iterable<Object> its = yaml.loadAll(content);
                    for (Object it : its) {
                        ymlData = (Map<String, Object>) it;
                        break;
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                try (InputStream content = UpdateDoaminIpStarted.class.getClassLoader().getResourceAsStream("application.yml")) {
                    Yaml yaml = new Yaml(new Constructor(Map.class));
                    Iterable<Object> its = yaml.loadAll(content);
//                    List<UserEntity> userEntityList = new ArrayList<>();
                    for (Object it : its) {
                        ymlData = (Map<String, Object>) it;
                        break;
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
            if (ymlData.size() > 0) {
                ACCESS_KEY_ID = ymlData.getOrDefault("accessKey", "").toString();
                ACCESS_KEY_SECRET = ymlData.getOrDefault("accessSecret", "").toString();
                REGION_ID = ymlData.getOrDefault("regionID", "").toString();
                DOMIAN = ymlData.getOrDefault("domain", "").toString();

                String domainName = ymlData.getOrDefault("domainName", "").toString();
                if (StringUtils.isNotEmpty(domainName)) {
                    if (domainName.contains(",")) {
                        String[] strings = domainName.split(",");
                        for (String s1 : strings) {
                            UPDATE_DOMIANS.put(s1 + "." + DOMIAN, null);
                        }
                    } else {
                        UPDATE_DOMIANS.put(domainName + "." + DOMIAN, null);
                    }
                }
            }
//            ACCESS_KEY_ID =

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }


        try {
            DefaultProfile.addEndpoint(REGION_ID, REGION_ID, "Alidns", "alidns.aliyuncs.com");
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IClientProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        client = new DefaultAcsClient(profile);
    }

    public static Record getSubDomainRecord(String subDomain) {
        DescribeSubDomainRecordsRequest request = new DescribeSubDomainRecordsRequest();
        DescribeSubDomainRecordsResponse response;
        request.setSubDomain(subDomain);
        try {
            response = client.getAcsResponse(request);
            List<Record> domainRecords = response.getDomainRecords();
            // {RR=mobile, recordId=4031722341639808, line=default, domainName=baidu.com,
            return domainRecords.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void updateDomainIp() {
        String ip = getIp();
        File file = null;
        try {

            file = new File(jarPath + "lastip.dat");
            System.out.println(file.getPath());
            if (file.exists()) {
                FileReader fileReader = new FileReader(file);
                BufferedReader br = new BufferedReader(fileReader);
                String lastIp = br.readLine();
                br.close();
                fileReader.close();
                if (lastIp.equals(ip)) {
                    System.out.println("ip没变：" + ip);
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("newIp:" + ip);
        UpdateDomainRecordRequest request;
        UpdateDomainRecordResponse response;
        String aa = "";
        for (String updateDomian : UPDATE_DOMIANS.keySet()) {
            if (UPDATE_DOMIANS.get(updateDomian) == null) {
                UPDATE_DOMIANS.put(updateDomian, getSubDomainRecord(updateDomian).getRecordId());
            }
            aa = updateDomian.replaceAll(DOMIAN, "").equals("") ? "@" : updateDomian.replaceAll("." + DOMIAN, "");
            request = new UpdateDomainRecordRequest();
            request.setRecordId(UPDATE_DOMIANS.get(updateDomian));
            request.setRR(aa);
            request.setType("A");
            request.setValue(ip);
            try {
                response = client.getAcsResponse(request);
                System.out.println(new Date().toString() + "：成功把" + updateDomian + "的域名的ip解析成" + ip);
//                System.out.println(response.getRequestId());
                if (file != null) {
                    FileWriter fileWriter = new FileWriter(file);
                    fileWriter.write(ip);
                    fileWriter.close();
                }
            } catch (ClientException e) {
                if (file != null) {
                    try {
                        System.out.println("DNS已经解析到这个ip了");
                        FileWriter fileWriter = new FileWriter(file);
                        fileWriter.write(ip);
                        fileWriter.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getIp() {
        return HttpUtil.get("http://ip.3322.net");
//        String ip = HttpUtil.get("http://myhost.mine.com/json_ip"); //替换成自己的，比较保险
//        if (!StringUtils.isEmpty(ip) && ip.startsWith("{")) {
//            JsonObject jsonObject = new JsonObject();
//            Gson gson = new Gson();
//            Map<String, String> map = gson.fromJson(ip, Map.class);
//            ip = map.getOrDefault("ip", "");
//        } else {
//            return HttpUtil.get("http://ip.3322.net");
//        }
//        return ip;
    }

    public static void main(String[] args) {
        while (true) {
            System.out.println(new Date().toString() + "：进入服务");
            try {
                updateDomainIp();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}